/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.continew.admin.hanfu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.continew.admin.hanfu.core.oss.OSS;
import top.continew.admin.hanfu.domain.OssFile;
import top.continew.admin.hanfu.domain.Sample;
import top.continew.admin.hanfu.domain.bo.SampleBo;
import top.continew.admin.hanfu.domain.dto.SampleDto;
import top.continew.admin.hanfu.domain.query.SampleQuery;
import top.continew.admin.hanfu.domain.vo.SampleVo;
import top.continew.admin.hanfu.domain.vo.wx.SampleDeWxVo;
import top.continew.admin.hanfu.domain.vo.wx.SampleWxVo;
import top.continew.admin.hanfu.mapper.SampleMapper;
import top.continew.admin.hanfu.service.ISampleService;

import java.util.Arrays;
import java.util.List;

import static top.continew.admin.common.util.OssIdClearUtils.cleanFrontCover;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xieling
 * @version 1.0
 * @since 2025/04/01 10:08
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SampleServiceImpl extends ServiceImpl<SampleMapper, Sample> implements ISampleService {

    private final SampleMapper sampleMapper;

    private final OSS oss;

    @Override
    public Page<SampleVo> getSampleListByCondition(SampleQuery sampleQuery) {
        // 清理和验证查询条件
        if (sampleQuery.getSampleType() != null) {
            sampleQuery.setSampleType(sampleQuery.getSampleType().trim());
        }
        if (sampleQuery.getSampleClassName() != null) {
            sampleQuery.setSampleClassName(sampleQuery.getSampleClassName().trim());
        }
        if (sampleQuery.getTitle() != null) {
            sampleQuery.setTitle(sampleQuery.getTitle().trim());
        }
        if (sampleQuery.getUploader() != null) {
            sampleQuery.setUploader(sampleQuery.getUploader().trim());
        }

        SampleBo sampleBo = new SampleBo();
        sampleBo.setSampleClassName(sampleQuery.getSampleClassName());
        sampleBo.setSampleType(sampleQuery.getSampleType());
        sampleBo.setApply(sampleQuery.getApply());
        sampleBo.setTitle(sampleQuery.getTitle());
        sampleBo.setAddress(sampleQuery.getAddress());
        sampleBo.setUploader(sampleQuery.getUploader());
        sampleBo.setStatus(sampleQuery.getStatus());
        sampleBo.setPhotographer(sampleQuery.getPhotographer());

        log.info("sampleBo:{}", sampleBo);

        return sampleMapper.getSampleListByCondition(new Page<>(sampleQuery.getPageNum(), sampleQuery
            .getPageSize()), sampleBo);
    }

    @Override
    public SampleVo getSampleById(Integer id) {
        return sampleMapper.getSampleDeVoById(id);
    }

    // ... existing code ...

    @Override
    public int addSample(SampleDto sampleDto) {
        // 清理front_cover数据
        if (sampleDto.getFrontCover() != null) {
            sampleDto.setFrontCover(cleanFrontCover(sampleDto.getFrontCover()));
        }

        Sample sample = BeanUtil.copyProperties(sampleDto, Sample.class);
        boolean save = save(sample);

        log.info("sample:{}", sample);

        return save ? sample.getId() : -1;
    }

    /**
     * 更新样片封面图片
     */
    @Override
    public int updateSampleImg(SampleBo sampleBo) {
        List<MultipartFile> image = sampleBo.getImage();
        MultipartFile[] array = image.toArray(new MultipartFile[image.size()]);

        // 清理和验证imageIds
        String imageIds = sampleBo.getImageIds();
        if (imageIds != null) {
            imageIds = imageIds.trim();
            if (imageIds.isEmpty()) {
                imageIds = "";
            }
        } else {
            imageIds = "";
        }

        List<String> newIds = new java.util.ArrayList<>(Arrays.stream(imageIds.split(","))
            .filter(id -> !id.trim().isEmpty())
            .map(String::trim)
            .toList());

        List<OssFile> ossFiles = oss.saveFile("sample", sampleBo.getUploader(), array);
        ossFiles.forEach(i -> {
            newIds.add(i.getOssId().toString());
        });

        Sample byId = getById(sampleBo.getId());
        String cleanedFrontCover = cleanFrontCover(byId.getFrontCover());
        List<String> list = Arrays.stream(cleanedFrontCover.split(","))
            .filter(id -> !id.trim().isEmpty())
            .map(String::trim)
            .toList();

        List<String> list1 = list.stream().filter(i -> !newIds.contains(i)).toList();

        oss.deleteFiles(list1);

        // 使用String.join替代StringBuilder
        String newFrontCover = String.join(",", newIds);
        byId.setFrontCover(newFrontCover);

        boolean update = lambdaUpdate().eq(Sample::getId, sampleBo.getId())
            .set(Sample::getFrontCover, byId.getFrontCover())
            .set(Sample::getUpdateTime, System.currentTimeMillis())
            .set(Sample::getUploader, sampleBo.getUploader())
            .update();

        return update ? 1 : 0;
    }

    /**
     * 更新样片
     */
    @Override
    public int updateSample(SampleDto sampleDto) {

        boolean update = lambdaUpdate().eq(Sample::getId, sampleDto.getId())
            .set(sampleDto.getSampleType() != null, Sample::getSampleType, sampleDto.getSampleType())
            .set(sampleDto.getApply() != null, Sample::getApply, sampleDto.getApply())
            .set(sampleDto.getDescription() != null, Sample::getDescription, sampleDto.getDescription())
            .set(sampleDto.getAddress() != null, Sample::getAddress, sampleDto.getAddress())
            .set(sampleDto.getAperture() != null, Sample::getAperture, sampleDto.getAperture())
            .set(sampleDto.getUpdateTime() != null, Sample::getUpdateTime, System.currentTimeMillis())
            .set(Sample::getUploader, sampleDto.getUploader())
            .set(sampleDto.getTitle() != null, Sample::getTitle, sampleDto.getTitle())
            .set(sampleDto.getCameraIso() != null, Sample::getCameraIso, sampleDto.getCameraIso())
            .set(sampleDto.getCameraLens() != null, Sample::getCameraLens, sampleDto.getCameraLens())
            .set(sampleDto.getCameraModel() != null, Sample::getCameraModel, sampleDto.getCameraModel())
            .set(sampleDto.getClothing() != null, Sample::getClothing, sampleDto.getClothing())
            .set(sampleDto.getModel() != null, Sample::getModel, sampleDto.getModel())
            .set(sampleDto.getShutter() != null, Sample::getShutter, sampleDto.getShutter())
            .set(sampleDto.getStatus() != null, Sample::getStatus, sampleDto.getStatus())
            .set(sampleDto.getPhotographer() != null, Sample::getPhotographer, sampleDto.getPhotographer())
            .update();

        return update ? sampleDto.getId() : 0;
    }

    @Override
    public Page<SampleWxVo> getSampleListByConditionWx(SampleQuery sampleQuery) {

        SampleBo sampleBo = new SampleBo();

        sampleBo.setSampleClassId(sampleQuery.getSampleClassId() == 0 ? null : sampleQuery.getSampleClassId());
        sampleBo.setTitle(sampleQuery.getTitle().isEmpty() ? null : sampleQuery.getTitle());

        return sampleMapper.getSampleListByConditionWx(new Page<>(sampleQuery.getPageNum(), sampleQuery
            .getPageSize()), sampleBo);
    }

    @Override
    public SampleDeWxVo getSampleDeWxVoById(Integer id) {

        return sampleMapper.getSampleDeWxVoById(id);
    }

}
